const myAxios = (config) => {
    return new Promise((resolve, reject) => {
        const {method , url , params , data} = config
        //1.声明一个xhr对象
        const xhr = new XMLHttpRequest()
        if (method.toUpperCase() === 'GET') {
            const str = setParams(params)
            //2.调用 open 方法 open(method,url)
            xhr.open('GET',params?url +'?' + str:url)
            //3.调用 send 方法 
            xhr.send()
        } else {
            let flag = Object.prototype.toString.call(data) === '[object Object]' 
            //2.调用 open 方法 open(method,url)
            xhr.open(method,url)
            //判断数据类型
            if(flag){
             xhr.setRequestHeader('Content-Type','application/json')
             xhr.send(JSON.stringify(data))
            }else {
             xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
             xhr.send(data)
            }
        }
       
        //4.监听xhr状态
    xhr.onreadystatechange = function () {
      if (xhr.readyState === 4)  {
        if (xhr.status >= 200 && xhr.status < 300) {
          resolve(JSON.parse(xhr.responseText))
        } else {
            reject('请求出错:' + xhr.status)
        }
    
    }
}
    })}

function setParams(obj) {
    let newArr = []
    for(let k in obj){
        const str = k + '=' + obj[k]
        newArr.push(str)
    }
    return newArr.join('&')
}
